package com.gjy.concurrency.beautiful;

import com.google.common.collect.Lists;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-06-13 10:52:13
 */
public class UtilTest {

    private static final Logger log = LoggerFactory.getLogger(UtilTest.class);

    @Test
    public void test3() throws InterruptedException {
        Semaphore semaphore = new Semaphore(3);

        semaphore.release();
        semaphore.acquire();
    }

    @Test
    public void test1() throws BrokenBarrierException, InterruptedException {

        CyclicBarrier cyclicBarrier = new CyclicBarrier(2, () -> {
            log.info("{}", "ccc");
        });

        cyclicBarrier.await();

    }

    @Test
    public void test2() throws InterruptedException {
        ArrayList<Runnable> list = Lists.newArrayList(
                () -> {
                    log.info("T1");
                },
                () -> {
                    log.info("T2");
                },
                () -> {
                    log.info("T3");
                },
                () -> {
                    log.info("T4");
                }
        );
        CountDownLatch cdl = new CountDownLatch(list.size());
        Arrange arrange = new Arrange(list, cdl);

        ExecutorService pool = Executors.newFixedThreadPool(1);
        pool.execute(arrange);

        cdl.await();

        pool.shutdown();
    }

    private static class Arrange implements Runnable {

        private final List<Runnable> list;
        private final CountDownLatch cdl;

        public Arrange(List<Runnable> list, CountDownLatch cdl) {
            this.list = list;
            this.cdl = cdl;
        }

        @Override
        public void run() {
            for (Runnable r : list) {
                r.run();
                cdl.countDown();
            }
        }
    }

    private static class Cdl implements Runnable {

        private final CountDownLatch cdl;

        public Cdl(CountDownLatch cdl) {
            this.cdl = cdl;
        }

        @Override
        public void run() {
            cdl.countDown();

        }
    }
}
